/**
 * Copyright (c) 2010 S9,Inc.All rights reserved.
 * Created by 2012-6-1 
 */
package cn.jdy.platform.service;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.jdy.framework.db.hibernate.BaseDao;
import cn.jdy.framework.exception.BaseException;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.util.StringUtil;
import cn.jdy.platform.entity.ConfValue;

/**
 * 项目配置部署
 *
 * @description :项目配置管理
 * @author: wuzhiliang
 * @data: 2013-7-11
 */
@Service
public class ConfService extends BaseDao<ConfValue> {

	/**
   * 根据分类typeid 查找对应配置项
   * @param typeid 必须
   * @param pid 可选
   * @return
   */
  @Cacheable(value = "cache1", key="'conf_' + #typeid + '_' + #pid")
  public List<ConfValue> queryByType(Integer typeid, Long pid) {
    return queryByType(typeid, pid,null);
  }
  
  public List<ConfValue> djgajListColumn(int typeid) {
		List<ConfValue> list;
		try {
			String sql = "select * from confvalue where typeid=:typeid and id not in(10409,10410,10411,10414,9795)order by sort asc";
			Query query = super.em().createSQLQuery(sql).addEntity(ConfValue.class);
			query.setParameter("typeid", typeid);
			list = query.list();
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "findUserColumn:获得用户文章栏目权限异常!", e);
			throw new BaseException("获得用户文章栏目权限异常!", e);
		}
		return list;
	}
  
  public List<ConfValue> lhkgajListColumn(int typeid) {
		List<ConfValue> list;
		try {
			String sql = "select * from confvalue where typeid=:typeid and id not in(10541,10549)order by sort asc";
			Query query = super.em().createSQLQuery(sql).addEntity(ConfValue.class);
			query.setParameter("typeid", typeid);
			list = query.list();
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "findUserColumn:获得用户文章栏目权限异常!", e);
			throw new BaseException("获得用户文章栏目权限异常!", e);
		}
		return list;
	}
  
  public List<ConfValue> xdgajListColumn(int typeid) {
		List<ConfValue> list;
		try {
			String sql = "select * from confvalue where typeid=:typeid and id not in(10531,10533)order by sort asc";
			Query query = super.em().createSQLQuery(sql).addEntity(ConfValue.class);
			query.setParameter("typeid", typeid);
			list = query.list();
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "xdgajListColumn:获得用户文章栏目权限异常!", e);
			throw new BaseException("获得用户文章栏目权限异常!", e);
		}
		return list;
	}
  
	/**
	 * 根据分类typeid 查找对应配置项
	 * @param typeid 必须
	 * @param pid 可选
	 * @return
	 */
	@Cacheable(value = "cache1", key="'conf_' + #typeid + '_' + #pid")
	public List<ConfValue> queryByType(Integer typeid, Long pid, Integer limitMax) {
		List<ConfValue> list = null;
		try {
			// 过滤与分页
		  DetachedCriteria dc = DetachedCriteria.forClass(entityClass);
		  dc.add(Restrictions.eq("typeid", typeid.longValue()));
			if(pid != null) {
			  dc.add(Restrictions.eq("pid", pid));
			}
			dc.addOrder(Order.asc("sort"));
			if(null == limitMax){
			  limitMax = 10000;// 默认最多取50条
			}
			list = super.find(dc, 0, limitMax);
		} catch(Exception e) {
		  e.printStackTrace();
			BaseLog.e(this.getClass(), "查找分类下的配置项异常", e);
		}
		return list;
	}

	/**
	 * 根据类型和名称 查找对应的配置数据
	 *
	 * @param typeid
	 * @param key
	 * @return
	 */
	@Cacheable(value = "cache1", key="'conf_' + #typeid + '_' + #key")
	public String findConfVal(String typeid, String key) {
		try {
			ConfValue cv = super.findOne("typeid", Long.valueOf(typeid), "keywords", key);
			if(cv != null) {
				return cv.getValue0();
			}
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "findconfval 查询参数项信息出错！", e);
		}
		return "";
	}

	/**
	 * 根据pid 查找对应子配置项
	 *
	 * @param pid
	 * @return
	 */
	@Cacheable(value = "cache1", key="'conf_pid' + #pid")
	public List<ConfValue> findConfValueByPid(Long pid) {
		DetachedCriteria dc = DetachedCriteria.forClass(super.entityClass);
		dc.add(Restrictions.eq("pid", pid));
		dc.addOrder(Order.asc("sort"));
		return super.find(dc);
	}

	/**
	 * 根据id 查找配置项
	 *
	 * @param id
	 * @return
	 */
	@Cacheable(value = "cache1", key="'conf_id' + #id")
	public ConfValue find(Serializable id) {
		return super.find(id);
	}

  /**
   * 删除 配置节点，如果该节点是父节点，会一并其子节点
   */
  @CacheEvict(value = "cache1", allEntries = true)
  @Override
  @Transactional
  public void delete(Serializable id) {
	  super.delete(id);
	  super.delete("pid",id);
  }

  /**
   * 更新
   */
  @CacheEvict(value = "cache1", allEntries = true)
  @Override
  @Transactional
  public void update(ConfValue entity) {
    super.update(entity);
  }
	
	/**
	 * 根据分类typeid 查找对应配置项
	 *
	 * @return
	 */
	public List<ConfValue> queryConfValueByPid(Integer typeid, Long pid,String childrenIds,String levels) {
		List<ConfValue> list = null;
		try {
			String sql ="SELECT  *  FROM  ConfValue confvalue0_  where 1=1 ";
				
				if(!StringUtil.isNullOrEmpty(typeid)){
				  sql+=" and  confvalue0_.typeid = "+typeid;
				}	
				if(!StringUtil.isNullOrEmpty(pid)&&StringUtil.isNullOrEmpty(childrenIds)){
				  sql+=" AND ( confvalue0_.pid = "+pid+" OR confvalue0_.pid IN( SELECT t1.id  FROM confvalue t1 WHERE t1.pid="+pid+" ) )";
				}
				if(!StringUtil.isNullOrEmpty(childrenIds)){
					sql+=" AND confvalue0_.pid in ("+childrenIds+")";
				}
				if(!StringUtil.isNullOrEmpty(levels)){
				  sql+=" and  confvalue0_.levels = "+levels;
				}	
				sql+=" order by confvalue0_.sort ASC ";
				org.hibernate.SQLQuery sqlQuery = em().createSQLQuery(sql);
				sqlQuery.addEntity(ConfValue.class);
				list = sqlQuery.list();
				
				
		} catch (Exception e) {
			BaseLog.e(this.getClass(), "查找分类下的配置项异常！", e);
		}
		return list;
	}
	
	/**
	 * 根据分类levels 查找对应配置项
	 *
	 * @return
	 */
  public List<ConfValue> queryConfValueByLevels(String levels, int displayStart, int displayLength) {
    List<ConfValue> list = null;
    try {
      DetachedCriteria dc = DetachedCriteria.forClass(entityClass);
      if (!StringUtil.isNullOrEmpty(levels)) {
        dc.add(Restrictions.eq("levels", levels));
      }
      dc.addOrder(Order.asc("sort"));

      list = super.find(dc, displayStart, displayLength);
    } catch (Exception e) {
      BaseLog.e(this.getClass(), "根据分类levels查找对应配置项异常！", e);
    }
    return list;
  }
	
	/**
	 * 根据分类levels 查找总记录数
	 *
	 * @return
	 */
	public Long queryConfValueCount(String levels) {
		try {
			return super.count("levels", levels);
		} catch (Exception e) {
			BaseLog.e(this.getClass(), "查找分类总记录数异常！", e);
		}
		return null;
	}
}
